// 数据库初始化脚本
require('dotenv').config();
const bcrypt = require('bcryptjs');
const { sequelize, User, UserProfile, Activity, Badge } = require('./models');

// 默认环境变量配置
process.env.JWT_SECRET = process.env.JWT_SECRET || 'dev_secret_key_1234567890';
process.env.DB_HOST = process.env.DB_HOST || 'localhost';
process.env.DB_PORT = process.env.DB_PORT || '3306';
process.env.DB_NAME = process.env.DB_NAME || 'campus_platform';
process.env.DB_USER = process.env.DB_USER || 'root';
process.env.DB_PASSWORD = process.env.DB_PASSWORD || '';

// 初始化数据库并创建基础数据
async function initializeDatabase() {
  try {
    console.log('连接数据库...');
    
    // 测试数据库连接
    await sequelize.authenticate();
    console.log('数据库连接成功');
    
    // 同步数据库模型（强制重建表）
    console.log('同步数据库模型...');
    await sequelize.sync({ force: true });
    console.log('数据库同步完成');
    
    // 创建测试用户
    console.log('创建测试用户...');
    
    // 1. 创建普通用户
    const saltRounds = 10;
    const hashedPassword = await bcrypt.hash('password123', saltRounds);
    
    const user = await User.create({
      email: 'user@example.com',
      password_hash: hashedPassword,
      username: 'testuser',
      role: 'user',
      is_active: true,
      last_login: new Date()
    });
    
    await UserProfile.create({
      user_id: user.id,
      interests: ['编程', '音乐', '篮球'],
      activity_preferences: { types: ['科技', '文艺', '体育'] },
      location_preference: '校内',
      preferred_time_slots: ['晚上', '周末'],
      activity_frequency: 'medium',
      social_level: 'ambivert'
    });
    
    // 2. 创建管理员用户
    const adminPassword = await bcrypt.hash('admin123', saltRounds);
    
    const admin = await User.create({
      email: 'admin@example.com',
      password_hash: adminPassword,
      username: 'admin',
      role: 'admin',
      is_active: true,
      last_login: new Date()
    });
    
    await UserProfile.create({
      user_id: admin.id,
      interests: ['系统管理', '活动组织', '数据分析'],
      activity_preferences: { types: ['科技', '管理'] },
      location_preference: '全校',
      preferred_time_slots: ['全天'],
      activity_frequency: 'high',
      social_level: 'extrovert'
    });
    
    // 3. 创建示例活动
    console.log('创建示例活动...');
    
    const activities = [
      {
        title: '校园歌手大赛',
        description: '一年一度的校园歌手大赛，欢迎所有热爱音乐的同学参加！',
        location: '大学生活动中心',
        start_time: new Date(2023, 5, 15, 18, 30),
        end_time: new Date(2023, 5, 15, 21, 30),
        category_id: 1,
        max_participants: 100,
        status: 'published',
        created_by: admin.id,
        image_url: '/images/default-event.jpg'
      },
      {
        title: '编程马拉松',
        description: '48小时不间断编程挑战，锻炼你的编程能力和团队协作！',
        location: '计算机学院实验室',
        start_time: new Date(2023, 6, 10, 9, 0),
        end_time: new Date(2023, 6, 12, 9, 0),
        category_id: 2,
        max_participants: 50,
        status: 'published',
        created_by: admin.id,
        image_url: '/images/default-event.jpg'
      },
      {
        title: '校园篮球联赛',
        description: '各院系组队参加的篮球联赛，展示你的球技！',
        location: '体育馆',
        start_time: new Date(2023, 7, 5, 14, 0),
        end_time: new Date(2023, 8, 20, 18, 0),
        category_id: 3,
        max_participants: 120,
        status: 'published',
        created_by: admin.id,
        image_url: '/images/default-event.jpg'
      }
    ];
    
    for (const activityData of activities) {
      await Activity.create(activityData);
    }
    
    // 4. 创建示例徽章
    console.log('创建示例徽章...');
    
    const existingActivities = await Activity.findAll();
    const activityIds = existingActivities.map(a => a.id);
    
    const badges = [
      {
        user_id: user.id,
        activity_id: activityIds[0] || 1,  // 使用第一个活动ID
        badge_name: '新手上路',
        badge_description: '完成第一次活动参与',
        badge_image_url: '/images/badges/beginner.png',
        rarity: 'common',
        status: 'minted',
        minted_at: new Date()
      },
      {
        user_id: user.id,
        activity_id: activityIds[1] || 2,  // 使用第二个活动ID
        badge_name: '活跃参与者',
        badge_description: '参与超过5次活动',
        badge_image_url: '/images/badges/active.png',
        rarity: 'uncommon',
        status: 'minted',
        minted_at: new Date()
      },
      {
        user_id: admin.id,
        activity_id: activityIds[2] || 3,  // 使用第三个活动ID
        badge_name: '系统管理员',
        badge_description: '系统管理员专属徽章',
        badge_image_url: '/images/badges/admin.png',
        rarity: 'legendary',
        status: 'minted',
        minted_at: new Date()
      }
    ];
    
    for (const badgeData of badges) {
      await Badge.create(badgeData);
    }
    
    console.log('数据库初始化完成！');
    console.log('');
    console.log('=== 测试账号 ===');
    console.log('普通用户:');
    console.log('  邮箱: user@example.com');
    console.log('  密码: password123');
    console.log('管理员:');
    console.log('  邮箱: admin@example.com');
    console.log('  密码: admin123');
    
  } catch (error) {
    console.error('数据库初始化失败:', error);
    process.exit(1);
  } finally {
    process.exit(0);
  }
}

// 执行初始化
initializeDatabase(); 